// pages/buy/order/order.js
const app = getApp()
const utils = require('../../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    way: ['全款', '贷款'],
    way_index: 0,
    total: '***',

    name: "",
    phone: "",
    card: "",
    date: utils.formatTime(new Date()).date

  },
  async add_img() {
    // const zheng = await wx.cloud.uploadFile({
    //   cloudPath: "img/" + new Date().getTime() + "-" + Math.floor(Math.random() * 1000),
    //   filePath: this.data.zheng
    // }).then(res => {
    //   return res.fileID
    // })
    // const water = await wx.cloud.uploadFile({
    //   cloudPath: "img/" + new Date().getTime() + "-" + Math.floor(Math.random() * 1000),
    //   filePath: this.data.water
    // }).then(res => {
    //   return res.fileID
    // })
    // const hun = await wx.cloud.uploadFile({
    //   cloudPath: "img/" + new Date().getTime() + "-" + Math.floor(Math.random() * 1000),
    //   filePath: this.data.hun
    // }).then(res => {
    //   return res.fileID
    // })
    // const card_front = await wx.cloud.uploadFile({
    //   cloudPath: "img/" + new Date().getTime() + "-" + Math.floor(Math.random() * 1000),
    //   filePath: this.data.card_front
    // }).then(res => {
    //   return res.fileID
    // })
    // const card_back = await wx.cloud.uploadFile({
    //   cloudPath: "img/" + new Date().getTime() + "-" + Math.floor(Math.random() * 1000),
    //   filePath: this.data.card_back
    // }).then(res => {
    //   return res.fileID
    // })
    // return {
    //   zheng,
    //   water,
    //   hun,
    //   card_front,
    //   card_back
    // }
  },
  choose_img(e) {
    let type = e.currentTarget.dataset.type
    let _this = this;
    let appInstance = getApp()
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(res,'res')
        let temp = res.tempFilePaths[0]
        wx.uploadFile({
          url: appInstance.globalData.requestUrl+'/wx/common/uploadFile',
          filePath: temp,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success (res){
            const data = JSON.parse(res.data)
            _this.setData({
              [type]: data.url
            })
          }
        })

      },
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let goods = wx.getStorageSync('goods')
    console.log(goods,'goods')
    this.setData({ goods, total: goods.price * 0.3 })

  },
  change_way(e) {
    let way_index = e.detail.value
    let total = way_index == '0' ? this.data.goods.price * 0.3 : 0
    this.setData({ way_index, total })
  },
  handle_name(e) {
    this.setData({
      name: e.detail.value
    })
  },
  handle_phone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  handle_card(e) {
    this.setData({
      card: e.detail.value
    })
  },
  go_pay() {
    let _this = this;
    let obj = {
      name: this.data.name,
      card: this.data.card,
      phone: this.data.phone
    }
    if (Object.values(obj).includes("")) {
      wx.showToast({
        title: '请完善订单信息',
        icon: "none"
      })
    }
    else if (!this.data.zheng || !this.data.water || !this.data.hun || !this.data.card_front || !this.data.card_back) {
      wx.showToast({
        title: '请完善个人信息',
        icon: "none"
      })
    }
    else {
      wx.showLoading({
        title: "模拟支付...",
        success: res => {
          this.add_img().then(imgs_mess => {
            // let data = {
            //   imgs_mess,
            //   name: this.data.name,
            //   card: this.data.card,
            //   phone: this.data.phone,
            //   way: this.data.way[this.data.way_index],
            //   total: this.data.total,
            //   goods: this.data.goods,
            //   pay_date:this.data.date
            // }
            // app.get('add_order', data).then(res => {
            //   wx.hideLoading()
            //   wx.showToast({
            //     title: res.msg,
            //     icon: "none"
            //   })
            //   setTimeout(() => {
            //     wx.navigateBack({
            //       delta: 2
            //     })
            //   }, 1000);
            // })
            console.log(imgs_mess,'imgs_mess')
            let args = wx.getStorageSync('args')
            let appInstance = getApp()
            wx.request({
              url: appInstance.globalData.requestUrl+'/wx/biz/add_order',
              data: {
                // imgs_mess,
                name: _this.data.name,
                card: _this.data.card,
                phone: _this.data.phone,
                way: _this.data.way[this.data.way_index],
                total: _this.data.total,
                goods: _this.data.goods,
                goodsId:_this.data.goods.id,
                pay_date:_this.data.date,
                "zheng": _this.data.zheng, //征信报告
                "water": _this.data.water, //银行流水
                "hun": _this.data.hun, //结婚证/单身证
                "cardFront": _this.data.card_front, //身份证（正面）
                "cardBack": _this.data.card_back //身份证（反面）
              },
              method:'POST',
              header: {
                'content-type': 'application/json', // 默认值
                'Authorization': 'Bearer '+ args.loginToken
              },
              success (res) {
                wx.hideLoading()
                wx.showToast({
                  title: res.data.msg,
                  icon: "none"
                })
                if(res.data.code == '200'){
                  setTimeout(() => {
                    wx.navigateBack({
                      delta: 2
                    })
                  }, 1000);
                }
              }
            })
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
